package bkt.framework.tool;

import java.util.Random;

import bkt.framework.FrameworkConstants;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

public class FrameworkSecurityUtil {

	public static synchronized String getApplicationRandomKey(Context context,String sharedPreferencesName,String appStaticSecureKey) {
		
		String randomKey = null;
		
		SharedPreferences appSharedPreferences = context.getSharedPreferences(sharedPreferencesName, Application.MODE_PRIVATE);
		
		if(appSharedPreferences != null){
			String appSecureKeyDecoded = appSharedPreferences.getString(appStaticSecureKey,null);
			if(!TextUtils.isEmpty(appSecureKeyDecoded)){
				try {
					randomKey = new String(Base64.decode(appSecureKeyDecoded.getBytes(), FrameworkConstants.ENCODE_DECODE_MODE_BASE64));
				} catch (Exception e) {
					Log.e(FrameworkConstants.LOGTAG_FRAMEWORK_SECURITY_UTIL,"Base 64 Decode Error",e);
				}
			}else{
				Log.w(FrameworkConstants.LOGTAG_FRAMEWORK_SECURITY_UTIL,"Decoded Key Not Found or First Calling");
			}
		}
		
		if(TextUtils.isEmpty(randomKey)){
			
			randomKey = ""+new Random().nextLong();
			
			if(TextUtils.isEmpty(randomKey)){
				randomKey = FrameworkConstants.DEFAULT_SECURITY_KEY;
			}
			SharedPreferences.Editor editor = null;
			
			try {
				editor = appSharedPreferences.edit();
				String appSecureKeyEncoded = Base64.encodeToString(randomKey.getBytes(), FrameworkConstants.ENCODE_DECODE_MODE_BASE64);
				editor.putString(appStaticSecureKey,appSecureKeyEncoded);
				editor.commit();
			} catch (Exception e) {
				Log.e(FrameworkConstants.LOGTAG_FRAMEWORK_SECURITY_UTIL,"Base 64 Encode Error",e);
			} finally{
				editor = null;
			}
		}
		
		appSharedPreferences = null;
		
		return randomKey;
	}

}
